import { ElMessage } from 'element-plus'
import { computed } from 'vue'

/**
 * 关系操作管理 composable
 * 处理各种实体间关系管理的业务逻辑
 */
export function useRelationOperations({
  // 选择状态
  selectedPageId,
  selectedCategoryId,
  selectedCategoryIdForItem,
  selectedItemId,
  selectedItemToAdd,
  selectedItemToRelate,
  selectedCategoryToRelate,
  selectedCategoryForPage,
  selectedItemForCategory,
  
  // 当前关系数据
  currentPageCategories,
  currentCategoryItems,
  currentItemCategories,
  currentRelatedItems,
  
  // 临时关系数据
  tempCategoryRelations,
  tempItemRelations,
  
  // 基础数据
  categories,
  items,
  hierarchyData,
  
  // 表单数据
  pageForm,
  categoryForm,
  itemForm,
  
  // 当前实体
  currentCategory,
  
  // 数据操作方法
  manageCategoryPageRelation,
  manageItemCategoryRelation,
  addItemToPageItem,
  removeItemFromPageItem,
  getPageItemRelations,
  
  // 数据更新方法
  fetchCategories,
  fetchHierarchyData,
  updateCurrentCategoryItems,
  updateAvailableItemsForCategory
}) {
  
  // 关系管理方法
  const addPageCategoryRelation = async () => {
    if (!selectedPageId.value || !selectedCategoryId.value) return
    
    await manageCategoryPageRelation(selectedCategoryId.value, selectedPageId.value, 'add')
    selectedCategoryId.value = null
  }

  const removePageCategoryRelation = async () => {
    if (!selectedPageId.value || !selectedCategoryId.value) return
    
    await manageCategoryPageRelation(selectedCategoryId.value, selectedPageId.value, 'remove')
    selectedCategoryId.value = null
  }

  const removePageCategoryRelationById = async (pageId, categoryId) => {
    await manageCategoryPageRelation(categoryId, pageId, 'remove')
  }

  const addCategoryItemRelation = async () => {
    if (!selectedCategoryIdForItem.value || !selectedItemId.value) return
    
    await manageItemCategoryRelation(selectedCategoryIdForItem.value, selectedItemId.value, 'add')
    selectedItemId.value = null
  }

  const removeCategoryItemRelation = async () => {
    if (!selectedCategoryIdForItem.value || !selectedItemId.value) return
    
    await manageItemCategoryRelation(selectedCategoryIdForItem.value, selectedItemId.value, 'remove')
    selectedItemId.value = null
  }

  // 页面项目关联管理方法
  const addItemRelation = async (pageItemId, relatedItemId) => {
    if (!pageItemId || !relatedItemId) return
    
    try {
      await addItemToPageItem(pageItemId, relatedItemId)
      
      // 添加到当前关联列表
      const itemToAdd = items.value.find(item => item.id === relatedItemId)
      if (itemToAdd) {
        currentRelatedItems.value.push(itemToAdd)
      }
      
      ElMessage.success('关联项目添加成功')
      
      // 清空选择
      selectedItemToRelate.value = null
      
      // 刷新当前关联项目列表
      await fetchCurrentRelatedItems(pageItemId)
    } catch (error) {
      ElMessage.error('关联项目添加失败')
    }
  }

  const removeItemRelation = async (pageItemId, relatedItemId) => {
    if (!pageItemId || !relatedItemId) return
    
    try {
      await removeItemFromPageItem(pageItemId, relatedItemId)
      
      // 从当前列表中移除关联项目
      const index = currentRelatedItems.value.findIndex(item => item.id === relatedItemId)
      if (index > -1) {
        currentRelatedItems.value.splice(index, 1)
      }
      
      ElMessage.success('关联项目移除成功')
      
      // 刷新当前关联项目列表
      await fetchCurrentRelatedItems(pageItemId)
    } catch (error) {
      ElMessage.error('关联项目移除失败')
    }
  }

  const removeCategoryItemRelationById = async (categoryId, itemId) => {
    await manageItemCategoryRelation(categoryId, itemId, 'remove')
  }

  const updateCurrentPageCategories = () => {
    if (!pageForm.id) return
    
    const pageData = hierarchyData.value.find(p => p.id === pageForm.id)
    currentPageCategories.value = pageData ? pageData.categories || [] : []
  }

  const addItemToCurrentCategory = async () => {
    if (!selectedItemToAdd.value || !currentCategory.value) return
    
    await manageItemCategoryRelation(currentCategory.value.id, selectedItemToAdd.value, 'add')
    selectedItemToAdd.value = null
    await new Promise(resolve => setTimeout(resolve, 100))
    await updateCurrentCategoryItems()
    updateAvailableItemsForCategory()
  }

  const removeItemFromCurrentCategory = async (itemId) => {
    if (!currentCategory.value) return
    
    await manageItemCategoryRelation(currentCategory.value.id, itemId, 'remove')
    await new Promise(resolve => setTimeout(resolve, 100))
    await updateCurrentCategoryItems()
    updateAvailableItemsForCategory()
  }

  // 表单弹窗中的关系管理方法
  const addCategoryToPage = async () => {
    const pageId = pageForm.id || pageForm.value?.id
    if (!selectedCategoryForPage.value || !pageId) return
    
    try {
      await manageCategoryPageRelation(selectedCategoryForPage.value, pageId, 'add')
      selectedCategoryForPage.value = null
      // 刷新当前页面的分类数据
      await new Promise(resolve => setTimeout(resolve, 100))
      updateCurrentPageCategories()
      ElMessage.success('关系添加成功')
    } catch (error) {
      ElMessage.error('关系添加失败')
      console.error('添加页面分类关系失败:', error)
    }
  }

  const removeCategoryFromPage = async (categoryId) => {
    const pageId = pageForm.id || pageForm.value?.id
    if (!pageId) return
    
    try {
      await manageCategoryPageRelation(categoryId, pageId, 'remove')
      // 刷新当前页面的分类数据
      await new Promise(resolve => setTimeout(resolve, 100))
      updateCurrentPageCategories()
      ElMessage.success('关系移除成功')
    } catch (error) {
      ElMessage.error('关系移除失败')
      console.error('移除页面分类关系失败:', error)
    }
  }

  const addItemToCategory = async () => {
    const categoryId = categoryForm.id || categoryForm.value?.id
    const itemId = selectedItemForCategory.value
    if (!itemId) return
    
    if (!categoryId) {
      if (!tempCategoryRelations.value.items.includes(itemId)) {
        tempCategoryRelations.value.items.push(itemId)
        ElMessage.success('项目关联已添加，将在保存分类后生效')
      } else {
        ElMessage.warning('该项目已在关联列表中')
      }
      selectedItemForCategory.value = null
      return
    }
    
    await updateCurrentCategoryItems()
    
    const isAlreadyRelated = currentCategoryItems.value.some(item => item.id === itemId)
    if (isAlreadyRelated) {
      ElMessage.warning('该项目已与分类关联')
      selectedItemForCategory.value = null
      return
    }
    
    try {
      await manageItemCategoryRelation(categoryId, itemId, 'add')
      selectedItemForCategory.value = null
      await new Promise(resolve => setTimeout(resolve, 200))
      await fetchCategories()
      await updateCurrentCategoryItems()
      updateAvailableItemsForCategory()
      ElMessage.success('关系添加成功')
    } catch (error) {
      ElMessage.error('关系添加失败')
      console.error('添加分类项目关系失败:', error)
    }
  }

  const removeItemFromCategory = async (itemId) => {
    const categoryId = categoryForm.id || categoryForm.value?.id
    
    if (!categoryId) {
      const index = tempCategoryRelations.value.items.indexOf(itemId)
      if (index > -1) {
        tempCategoryRelations.value.items.splice(index, 1)
        ElMessage.success('项目关联已移除')
      }
      return
    }
    
    // 如果是编辑分类，直接移除关联
    try {
      await manageItemCategoryRelation(categoryId, itemId, 'remove')
      // 等待数据刷新完成后再更新UI
      await new Promise(resolve => setTimeout(resolve, 200))
      // 重新获取分类数据以确保移除最新的项目关联
      await fetchCategories()
      await updateCurrentCategoryItems()
      updateAvailableItemsForCategory()
      ElMessage.success('关系移除成功')
    } catch (error) {
      ElMessage.error('关系移除失败')
    }
  }

  // 获取临时关联的项目
  const getTempRelatedItems = () => {
    return items.value.filter(item => tempCategoryRelations.value.items.includes(item.id))
  }

  // 获取当前页面项目的关联项目
  const getCurrentRelatedItems = (pageItemId) => {
    if (!pageItemId) return []
    return currentRelatedItems.value
  }

  // 移除页面项目关联
  const removePageItemRelation = async (pageItemId, itemId) => {
    try {
      await removeItemFromPageItem(pageItemId, itemId)
      ElMessage.success('关联项目移除成功')
      // 刷新层级数据
      await fetchHierarchyData()
    } catch (error) {
      ElMessage.error('移除关联项目失败')
    }
  }

  // 从API获取页面项目的关联项目
  const fetchCurrentRelatedItems = async (pageItemId) => {
    if (!pageItemId) {
      currentRelatedItems.value = []
      return
    }
    
    try {
      const result = await getPageItemRelations(pageItemId)
      currentRelatedItems.value = result.data?.related_items || []
    } catch (error) {
      currentRelatedItems.value = []
    }
  }

  // 获取可关联的项目列表（排除当前项目、已关联项目和其他页面类型项目）
  const availableItemsToRelate = computed(() => {
    const currentItemId = itemForm.id
    const relatedItemIds = currentRelatedItems.value.map(item => item.id)
    
    return items.value.filter(item => 
      (!currentItemId || item.id !== currentItemId) && // 新建模式下不排除任何项目，编辑模式下排除当前项目
      !relatedItemIds.includes(item.id) && // 排除已关联项目
      item.content_type !== 'page' // 排除其他页面类型项目
    )
  })

  // 获取可关联的分类列表（排除已关联的分类）
  const availableCategoriesToRelate = computed(() => {
    const relatedCategoryIds = currentItemCategories.value.map(category => category.id)
    
    return categories.value.filter(category => 
      !relatedCategoryIds.includes(category.id) // 排除已关联分类
    )
  })

  return {
    addPageCategoryRelation,
    removePageCategoryRelation,
    removePageCategoryRelationById,
    addCategoryItemRelation,
    removeCategoryItemRelation,
    addItemRelation,
    removeItemRelation,
    removeCategoryItemRelationById,
    updateCurrentPageCategories,
    addItemToCurrentCategory,
    removeItemFromCurrentCategory,
    addCategoryToPage,
    removeCategoryFromPage,
    addItemToCategory,
    removeItemFromCategory,
    getTempRelatedItems,
    getCurrentRelatedItems,
    removePageItemRelation,
    fetchCurrentRelatedItems,
    availableItemsToRelate,
    availableCategoriesToRelate
  }
}